/**
 * 注册所有node服务进入electron
 */
import {ipcMain} from 'electron'
import {
    createMysqlPool,
    executeMysqlQuery,
    executeMysqlBatchQuery,
    executeMysqlTransaction,
    closeMysqlPool,
    closeAllMysqlPools,
    getMysqlPoolStatus
} from '../driver/mysql.js'
import {
    createSqliteConnection,
    executeSqliteQuery,
    executeSqliteRun,
    executeSqliteBatchQuery,
    executeSqliteTransaction,
    executeSqliteScript,
    getSqliteTableInfo,
    optimizeSqliteDatabase,
    backupSqliteDatabase,
    closeSqliteConnection,
    closeAllSqliteConnections,
    getSqliteConnectionStatus
} from '../driver/sqlite.js'

import {initData} from '../system/dataSystem.js'
import {getPing} from '../system/getPing.js'

export const registerNodeService = () => {
    // MySQL 相关服务
    ipcMain.handle('mysql-create-pool', async (event, poolId, config) => {
        try {
            return await createMysqlPool(poolId, config)
        } catch (err) {
            throw new Error(err.message)
        }
    })

    ipcMain.handle('mysql-query', async (event, poolId, sql, params) => {
        try {
            return await executeMysqlQuery(poolId, sql, params)
        } catch (err) {
            return {
                success: false,
                error: err.message,
                data: [],
                fields: [],
                rowCount: 0
            }
        }
    })

    ipcMain.handle('mysql-batch-query', async (event, poolId, queries) => {
        try {
            return await executeMysqlBatchQuery(poolId, queries)
        } catch (err) {
            return [{
                success: false,
                error: err.message,
                data: [],
                fields: [],
                rowCount: 0
            }]
        }
    })

    ipcMain.handle('mysql-transaction', async (event, poolId, queries) => {
        try {
            return await executeMysqlTransaction(poolId, queries)
        } catch (err) {
            return {
                success: false,
                error: err.message,
                results: []
            }
        }
    })

    ipcMain.handle('mysql-close-pool', async (event, poolId) => {
        try {
            return await closeMysqlPool(poolId)
        } catch (err) {
            return false
        }
    })

    ipcMain.handle('mysql-pool-status', async (event, poolId) => {
        try {
            return getMysqlPoolStatus(poolId)
        } catch (err) {
            return {exists: false, error: err.message}
        }
    })

    // SQLite 相关服务
    ipcMain.handle('sqlite-create-connection', async (event, dbId, config) => {
        try {
            return await createSqliteConnection(dbId, config)
        } catch (err) {
            throw new Error(err.message)
        }
    })

    ipcMain.handle('sqlite-query', async (event, dbId, sql, params, single) => {
        try {
            return await executeSqliteQuery(dbId, sql, params, single)
        } catch (err) {
            return {
                success: false,
                error: err.message,
                data: single ? null : [],
                rowCount: 0
            }
        }
    })

    ipcMain.handle('sqlite-run', async (event, dbId, sql, params) => {
        try {
            return await executeSqliteRun(dbId, sql, params)
        } catch (err) {
            return {
                success: false,
                error: err.message,
                lastID: null,
                changes: 0
            }
        }
    })

    ipcMain.handle('sqlite-batch-query', async (event, dbId, queries) => {
        try {
            return await executeSqliteBatchQuery(dbId, queries)
        } catch (err) {
            return [{
                success: false,
                error: err.message,
                data: [],
                rowCount: 0
            }]
        }
    })

    ipcMain.handle('sqlite-transaction', async (event, dbId, queries) => {
        try {
            return await executeSqliteTransaction(dbId, queries)
        } catch (err) {
            return {
                success: false,
                error: err.message,
                results: []
            }
        }
    })

    ipcMain.handle('sqlite-script', async (event, dbId, script) => {
        try {
            return await executeSqliteScript(dbId, script)
        } catch (err) {
            return {
                success: false,
                error: err.message
            }
        }
    })

    ipcMain.handle('sqlite-table-info', async (event, dbId, tableName) => {
        try {
            return await getSqliteTableInfo(dbId, tableName)
        } catch (err) {
            return {
                success: false,
                error: err.message,
                data: null
            }
        }
    })

    ipcMain.handle('sqlite-optimize', async (event, dbId) => {
        try {
            return await optimizeSqliteDatabase(dbId)
        } catch (err) {
            return {
                success: false,
                error: err.message
            }
        }
    })

    ipcMain.handle('sqlite-backup', async (event, dbId, backupPath) => {
        try {
            return await backupSqliteDatabase(dbId, backupPath)
        } catch (err) {
            return {
                success: false,
                error: err.message
            }
        }
    })

    ipcMain.handle('sqlite-close-connection', async (event, dbId) => {
        try {
            return await closeSqliteConnection(dbId)
        } catch (err) {
            return false
        }
    })

    ipcMain.handle('sqlite-connection-status', async (event, dbId) => {
        try {
            return getSqliteConnectionStatus(dbId)
        } catch (err) {
            return {exists: false, error: err.message}
        }
    })

    /**
     * 系统数据库db
     */
    ipcMain.handle('systemDb', async (event, { sql, params }) => {
        try {
            const db = await initData()
            const stmt = db.prepare(sql)

            if (/^\s*select/i.test(sql)) {
                return stmt.all(params)
            } else {
                const result = stmt.run(params)
                return { changes: result.changes, lastInsertRowid: result.lastInsertRowid }
            }
        } catch (err) {
            return { success: false, error: err.message }
        }
    })

    /**
     * ping 地址
     */
    ipcMain.handle('ping',async (event,ip) => {
        return getPing(ip)
    })
}

// 应用退出时清理所有连接池
export const cleanup = async () => {
    try {
        await closeAllMysqlPools()
        await closeAllSqliteConnections()
        console.log('所有数据库连接池已清理')
    } catch (err) {
        console.error('清理数据库连接池失败:', err)
    }
}
